package kaug.loeng3;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class DrawPanel extends JPanel {
	
	class MyMouseListener extends MouseAdapter {

	}
	
	Color color = Color.BLACK;

	List<Point> points = new ArrayList<Point>();
	
	int closestPointIndex = -1;
	
	public DrawPanel() {
		setFocusable(true);
		requestFocus();
		
		setBackground(Color.WHITE);

		addMouseMotionListener(new MouseAdapter() {
			@Override
			public void mouseDragged(MouseEvent e) {
				if (e.isControlDown()) {
					// move
				} else {
					points.add(e.getPoint());
				}
				repaint();
			}
			
			@Override
			public void mouseMoved(MouseEvent e) {
				if (e.isControlDown()) {
					double bestDist = Double.MAX_VALUE;
					int bestIndex = -1;
					Point p = e.getPoint();
					for (int i = 0; i < points.size(); i++) {
						Point p2 = points.get(i);
						if (p2 != null) {
							double dist = p.distance(p2);
							if (dist < bestDist) {
								bestDist = dist;
								bestIndex = i;
							}
						}
					}
					if (bestIndex > -1) {
						closestPointIndex = bestIndex;
					}
					System.out.println("" + closestPointIndex);
					repaint();
				}
			}
		});
		
		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				points.add(null);
			}
		});
		
		addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				System.out.println(e.getKeyCode());
				if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
					int result = JOptionPane.showConfirmDialog(DrawPanel.this, "Exit?", "exit", JOptionPane.YES_NO_OPTION);
					if (result == JOptionPane.YES_OPTION) {
						System.exit(0);
					}
				}
				
			}
		});
		
		//addMouseListener(new MyMouseListener());
	}
	
	public void drawPoint(Point p) {
		Graphics g = getGraphics();
		g.drawLine(p.x, p.y, p.x, p.y);
		g.dispose();
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.setColor(color);
		g.drawLine(0, 0, 100, 100);
		Point last = null;
		for (int i = 0; i < points.size(); i++) {
			Point p = points.get(i);
			if (i == closestPointIndex) {
				g.setColor(Color.RED);
			} else {
				g.setColor(Color.BLACK);				
			}
			if (last != null && p != null) {
				g.drawLine(p.x, p.y, last.x, last.y);
			}
			last = p;
		}
	}
	
	public Color getColor() {
		return color;
	}
	
	public void setColor(Color color) {
		this.color = color;
		repaint();
	}
}
